#!/usr/bin/env python3
import os, sys, csv, queue, getopt
from datetime import date, datetime, timedelta
from configparser import ConfigParser
from multiprocessing import Process,Queue as q


class Args(object):

    def __init__(self):
        l = sys.argv[1:]
        options,args = getopt.getopt(l,'hC:c:d:o:',['help'])
        d = dict(options)
        if len(options) == 1 and list(d.keys())[0] in ['-h','--help']:
            print("Usage: calculator.py -C cityname -c configfile -d userdata -o resultdata")
            exit()
        if d.get("-C"):
            self.C = d["-C"].upper()
        else:
            self.C = "DEFAULT"
        self.c = d["-c"]
        self.d = d["-d"]
        self.o = d["-o"]
        


class Config(object):

    def __init__(self, path, city):
        self.path = path
        self.city = city
        self.config = self._a()

    def _a(self):
        d ={'s':0}
        config = ConfigParser()
        config.read(self.path)
        for m,n in config.items(self.city):
            if m == 'jishul' or m == 'jishuh':
                d[m] = float(n)
            else:
                d['s'] += float(n)
        print(d)
        return d

    def get_config(self, name):
        return self.config.get(name)
        

# class Config(object):

#     def __init__(self, path):
#         self.path = path
#         self.config = self._a()

    # def _a(self):
    #     d ={'s':0}
    #     with open(self.path) as f:
    #         for i in f.readlines():
    #             l = i.split("=")
    #             m,n = l[0].strip(),l[1].strip()
    #             if m == 'JiShuL' or m == 'JiShuH':
    #                 d[m] = float(n)
    #             else:
    #                 d['s'] += float(n)
    #     return d

#     def get_config(self, name):
#         return self.config.get(name)


arg = Args()
q1, q2=q(), q()


class UserData(object):

    def __init__(self, path):
        self.path = path
        self.userdata = self._read_users_data()

    def _read_users_data(self):
        userdata = {}
        if os.path.exists(os.path.join( os.getcwd(),self.path)):
            with open(self.path) as f:
                for line in f:
                    line = line.strip()
                    arr = line.split(',')
                    userdata[arr[0]]=arr[1]
        else:
            print("File no exist.")
            sys.exit()
        return userdata


class IncomeTaxCalculator(object):

    def __init__(self):
        self.cfg = Config(arg.c,arg.C)

    def calc_for_all_userdata(self,user):
        data = []
        a1 = [0,1500,4500,9000,35000,55000,80000]
        a2 = [0.03,0.1,0.2,0.25,0.3,0.35,0.45]
        a3 = [0,105,555,1005,2755,5505,13505]
        for key, value in user.items():
            d = [key,value]
            jisu = 0
            value = float(value)
            if value < self.cfg.get_config("jishul"):
                jisu = self.cfg.get_config("jishul")
            elif value > self.cfg.get_config("jishuh"):
                jisu = self.cfg.get_config("jishuh")
            else:
                jisu = value
            sb = jisu * (self.cfg.get_config("s"))
            d.append(format(sb, ".2f"))
            shui = 0
            value = float(value) - sb
            if value > 3500:
                for i in range(len(a1)):
                    if (value-3500) < a1[i]:
                       shui = (value-3500) * a2[i-1] - a3[i-1]
                       break
            value = value - shui
            d.append(format(shui, ".2f"))
            d.append(format(value, ".2f"))

            t = datetime.now()
            datetime.strftime(t, '%Y-%m-%d %H:%M:%S')
            d.append(t)
            data.append(d)
        data.reverse()
        return data


def f1():
    for key,value in UserData(arg.d).userdata.items():
        q1.put({key:value})


def f2():
    def haha():
        try:
            while True:
                x = IncomeTaxCalculator().calc_for_all_userdata(q1.get(timeout=0.1))
                yield x
        except queue.Empty:
            return
    for i in haha():
        print(i)
        q2.put(i)


def f3():
    with open(arg.o,'a') as f:
        while True:
            try:
                csv.writer(f).writerow(q2.get(timeout=0.1)) 
            except queue.Empty:
                return



if __name__ == '__main__':
    Process(target=f1).start()
    Process(target=f2).start()
    Process(target=f3).start()
